﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace Treinamento2015_01Core.Infrastucture
{
    public static class UnitOfWork
    {
        private const string UNIT_OF_WORK = "TREINAMENTO_UNIT_OF_WORK";
        private static readonly Hashtable _threads = new Hashtable();


        public static BaseContext Context
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    if (!HttpContext.Current.Items.Contains(UNIT_OF_WORK))
                    {
                        BaseContext container = new BaseContext();
                        HttpContext.Current.Items.Add(UNIT_OF_WORK, container);
                    }
                    return (BaseContext)HttpContext.Current.Items[UNIT_OF_WORK];
                }
                else
                {
                    Thread thread = Thread.CurrentThread;
                    if (string.IsNullOrEmpty(thread.Name))
                    {
                        thread.Name = Guid.NewGuid().ToString();
                    }
                    if (_threads[thread.Name] == null)
                    {
                        BaseContext container = new BaseContext();
                        _threads[thread.Name] = container;
                    }
                    return (BaseContext)_threads[thread.Name];
                }
            }
        }

        public static void Close()
        {
            if (Context != null)
            {
                Context.SaveChanges();
                Context.Dispose();
            }
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Items.Remove(UNIT_OF_WORK);
            }
            else
            {
                _threads.Remove(Thread.CurrentThread.Name);
            }


        }

    }
}
